let gulp = require('gulp'),
    uglify = require('gulp-uglify'),
    rename = require('gulp-rename'),
    minify = require('gulp-minify-css'),
    connect = require('gulp-connect'),
    watch = require('gulp-watch'),
    less = require("gulp-less"),
    concat = require('gulp-concat'),
    clean = require('gulp-clean'),
    imagemin = require('gulp-imagemin'),
    autoprefixer = require('gulp-autoprefixer'),
    rev = require('gulp-rev-dxb'),
    revCollector = require('gulp-rev-collector-dxb'),
    runSequence = require('run-sequence'),
    pngquant = require('imagemin-pngquant');
// 生成版本号清单
gulp.task('rev', function () {
    return gulp.src(['./dist/js/**', './dist/css/**'])
        .pipe(rev())
        .pipe(rev.manifest())
        .pipe(gulp.dest("./rev"));
});

gulp.task('uglifyjs', function () {
    return gulp.src('src/**/*.js')
        .pipe(uglify())
        .pipe(concat('index.js'))
        .pipe(rename({ suffix: '.min' }))
        .pipe(revCollector())
        .pipe(gulp.dest('dist/js'))
        .pipe(connect.reload())
})

gulp.task('cssminify', function () {
    return gulp.src('src/**/*.css')
        .pipe(minify())
        .pipe(rename({ suffix: '.min' }))
        .pipe(gulp.dest('dist'))
        .pipe(connect.reload())
})

gulp.task('less', function () {
    return gulp.src('src/less/*.less')
        .pipe(less())
        .pipe(minify())
        .pipe(concat('index.css'))
        .pipe(rename({ suffix: '.min' }))
        .pipe(autoprefixer({
            overrideBrowserslist: ['last 20 versions']
        }))
        .pipe(gulp.dest('dist/css'))
        .pipe(connect.reload())
})

// 图片处理
gulp.task('image', function () {
    gulp.src('src/img/**/**.*')
        .pipe(imagemin({
            optimizationLevel: 5, //类型：Number  默认：3  取值范围：0-7（优化等级）
            progressive: true, //类型：Boolean 默认：false 无损压缩jpg图片
            interlaced: true, //类型：Boolean 默认：false 隔行扫描gif进行渲染
            multipass: true //类型：Boolean 默认：false 多次优化svg直到完全优化
        }))
        .pipe(gulp.dest('dist/img'))
        .pipe(connect.reload())
})

// html处理
gulp.task('html', function () {
    return gulp.src(['rev/**/*.json', 'src/**/*.html'])
        .pipe(revCollector())
        .pipe(gulp.dest('dist'))
        .pipe(connect.reload())
})

// 清除
gulp.task('clean', function () {
    gulp.src('dist',{allowEmpty: true})
        .pipe(clean());
})

// 构建
gulp.task('build', gulp.parallel('uglifyjs', 'less', 'cssminify', 'image','rev','html'))

// 监听
gulp.task("watch", function () {//监听任务
    watch("src/**/*.*", gulp.parallel('build', function () {
        console.log('操作成功')
    }));
})

// 启动本地服务
gulp.task("server", function () {
    connect.server({
        root: "./dist",
        livereload: true,
        port: 8888
    })
})

gulp.task('default', gulp.parallel('server','watch',  function () {
    console.log('操作成功')
}))
